<?php
/**
 * 消息队列消费服务
 */
namespace app\service;
use think\Db;
use app\service\OrderService;
use app\service\UserWeixinService;
use app\service\TechnWeixinService;
use app\service\PaymentService;
class QueuesService
{
	/**
	 * 消费队列执行关闭未支付订单
	 */
	public function order_close(\think\queue\Job $job, $queues_data)
	{
		//删作队列
		$job->delete();
		//查询订单信息
		$order_info = Db::name('order')->where(['id' => $queues_data['id']])->find();
		if(empty($order_info))
        {
            exit();
        }
        if($order_info['status'] != 0)
        {
            exit();
        }
        //开启事务
        Db::startTrans();
        $upd_data = [
            'status'        => 15,//支付超时
            'close_time'   => time(),
            'upd_time'      => time(),
        ];
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
        	//事务回滚
        	Db::rollback();
            exit();
        }
        // 订单状态日志添加
        $status_array = OrderService::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $upd_data['status'],
			'msg' => '系统关闭['.$status_array[$order_info['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']',
			'identity_type' => 'system',
			'identity_id' => 0,
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
            exit();
		}
		//提交事务
		Db::commit();
	}
	
	
	/**
	 * 消费队列 服务结束提醒
	 */
	public function order_fw_close(\think\queue\Job $job, $queues_data)
	{
	    //删作队列
		$job->delete();
		//查询订单信息
		$order_info = Db::name('order')->where(['id' => $queues_data['id']])->find();
	    
	    if($order_info['status']!=5){
	        exit;
	    }
	    
	    if($order_info['pre_end_time']-time()>310){
	        exit;
	    }
	    
	    $openid = Db::name('user_weixin')->where(['user_id' => $order_info['user_id'],'identity_type'=>'user'])->value('openid');
        $tem_msg['touser'] = $openid;
        $tem_msg['template_id'] = 'i1sheff0vHc8p1iqiHqNJe1N0drRP7l_UYK53dJsYJA';
		$tem_msg['url'] = 'https://h5.hexukeji.com/h5/pages/order/orderdetail?order_id='.$queues_data['id'];
        $tem_msg['data'] = [
            'first' => [
                'value' => '您的服务剩余5分钟结束',
                'color' => '#173177'
            ],
            'keyword1' => [
                'value' => $order_info['order_no'],
                'color' => '#173177'
            ],
            'keyword2' => [
                'value' => date('Y-m-d H:i:s',$order_info['pre_start_time']),
                'color' => '#173177'
            ],
            'keyword3' => [
                'value' => date('Y-m-d H:i:s',$order_info['pre_end_time']),
                'color' => '#173177'
            ],
            'keyword4' => [
                'value' => '正常',
                'color' => '#173177'
            ],
            'remark' => [
                'value' => '感谢使用，欢迎再次使用',
                'color' => '#173177'
            ]
        ];
		UserWeixinService::send_wx_web_tem_msg($tem_msg);
	}
	
	
	
	/**
	 * 消费队列执行解绑关系
	 */
	public function yinsi_close(\think\queue\Job $job, $queues_data)
	{
		//删作队列
		$job->delete();
	
		$yinsi_phone = cache('yinsi_phone_'.$queues_data['mobile']);
        if(!empty($yinsi_phone))
        {
        	//解绑关系
        	$args = [
        		'poolKey' => 'FC100000167170034',
//        		'poolKey' => 'FC100000168856007',
        		'subsId' => $yinsi_phone['subsId'],
        		'secretNo' => $yinsi_phone['secretNo']
        	];
        	\yinsi\Privacy::UnbindSubscription($args);
        }
	}
	
	
	/**
	 * 消费队列执行电话通知
	 */
	public function ivrCall(\think\queue\Job $job, $queues_data)
	{
		//删作队列
		$job->delete();
        $order_info=db::name('order')->where('id',$queues_data['id'])->find();

        if($order_info['status'] ==1){
            ivrCall('LTAI5tCfyuqK4o58i6MH3qH2', 'xXOnPRM4tMimqDVR4e1Ms5crn0lUtP', '057156104394', $queues_data['mobile'], 'TTS_269350009');
        }
	}
	
	
	public function orderCall(\think\queue\Job $job, $queues_data)
	{
		//删作队列
		$job->delete();
		
		$order_info=db::name('order')->where('id',$queues_data['id'])->find();
		
		if($order_info['status']!=1){
            exit();
		}

//		 订单支付方式校验
        $pay_log = Db::name('pay_log')->where(['order_id' => $queues_data['id'], 'business_type' => 1])->find();
        if(empty($pay_log))
        {
        	echo json_encode(['code' => -100, 'msg' => '支付日志不存在']);
			exit();
        }
        $refund_price = $order_info['pay_price'];

        $pay_status = 2;

        //判断是否为余额支付
        $is_money = false;
        if($pay_log['payment'] == 'MoneyPay')
        {
        	//是
        	$is_money = true;
        }else
        {
        	//否，原路退回
        	// 操作退款
        	$payment_array = PaymentService::$payment_array;
        	$payment = $payment_array[$order_info['payment_id']];
        	$pay_name = 'payment\\'.$payment['payment'];
        	$pay_params = [
        		'order_id'          => $order_info['id'],
        		'order_no'          => $order_info['order_no'],
        		'trade_no'          => $pay_log['trade_no'],
        		'pay_price'         => $order_info['pay_price'],
        		'refund_price'      => $refund_price,
        		'client_type'       => $order_info['client_type'],
        		'refund_reason'     => $order_info['order_no'].'订单退款'.$refund_price.'元',
        		'pay_time'          => $order_info['pay_time'],
        	];
        	$refund = (new $pay_name($payment['config']['user']))->Refund($pay_params);
        }
        // 退款成功
        if(isset($refund['code']) && $refund['code'] != 0)
        {
            echo json_encode($refund);
			exit();
        }

	    // 开启事务
        Db::startTrans();
	//退款日志数据
        $refund_log_data = [];
        // 余额退款
        if($is_money === true)
        {
        	// 获取用户余额
        	$user_info = Db::name('user')->where(['id' => $order_info['user_id']])->find();
        	if(empty($user_info))
        	{
        		Db::rollback();
        		echo json_encode(['code' => -100, 'msg' => '用户不存在']);
			    exit();
        	}
        	// 更新余额数据
        	$money_data = [
	            'money' => Db::raw('money+'.$refund_price),
	            'upd_time' => time()
	        ];
	        if(!Db::name('user')->where(['id' => $user_info['id']])->update($money_data))
	        {
	            Db::rollback();
	            echo json_encode(['code' => -100, 'msg' => '余额操作失败']);
			    exit();
	        }
	        //余额日志
	        $money_log_id = Db::name('money_log')->insertGetId([
	            'identity_type' => 'user',
	            'identity_id' => $user_info['id'],
	            'business_type' => 2,
	            'money_type' => 0,
	            'operation_type' => 1,
	            'operation_money' => $refund_price,
	            'original_money' => $user_info['money'],
	            'latest_money' => $user_info['money']+$refund_price,
	            'msg' => '订单超时退款',
	            'add_time' => time()
	        ]);
	        if($money_log_id <= 0)
	        {
	            Db::rollback();
	            echo json_encode(['code' => -100, 'msg' => '余额日志添加失败']);
			    exit();
	        }
	        $refund_log_data = [
	        	'order_id' => $order_info['id'],
	        	'trade_no' => '',
	        	'buyer_user' => '',
	        	'refund_price' => $refund_price,
	        	'pay_price' => $order_info['pay_price'],
	        	'msg' => '订单退款',
	        	'payment' => $pay_log['payment'],
	        	'payment_name' => $pay_log['payment_name'],
	        	'refundment' => 0,
	        	'business_type' => 1,
	        	'return_params' => '',
	        	'add_time' => time(),
        		'uid'=>$order_info['user_id'],
			    'reason'=>empty($params['reason'])?'超时退款':$params['reason'],
			    'day'=>date('Y-m-d')
	        ];
        }else
        {
        	$refund_log_data = [
        		'order_id' => $order_info['id'],
        		'trade_no' => isset($refund['data']['trade_no']) ? $refund['data']['trade_no'] : '',
        		'buyer_user' => isset($refund['data']['buyer_user']) ? $refund['data']['buyer_user'] : '',
        		'refund_price' => isset($refund['data']['refund_price']) ? $refund['data']['refund_price'] : '',
        		'pay_price' => $order_info['pay_price'],
        		'msg' => '订单退款',
        		'payment' => $pay_log['payment'],
        		'payment_name' => $pay_log['payment_name'],
        		'refundment' => 0,
        		'business_type' => 1,
        		'return_params' => isset($refund['data']['return_params']) ? json_encode($refund['data']['return_params'], JSON_UNESCAPED_UNICODE) : '',
        		'add_time' => time(),
        		'uid'=>$order_info['user_id'],
			    'reason'=>empty($params['reason'])?'':$params['reason'],
			    'day'=>date('Y-m-d')
        	];
        }
        //写入退款日志
        $refund_log_id = Db::name('refund_log')->insertGetId($refund_log_data);
        if($refund_log_id <= 0)
        {
        	Db::rollback();
        	echo json_encode(['code' => -100, 'msg' => '退款日志添加失败']);
			exit();
        }
        // 更新主订单
        $order_upd_data = [
        	'pay_status' => $pay_status,
        	'refund_price' => $refund_log_data['refund_price'],
        	'status' => 17,//技师不接单
        	'close_time' => time(),
        	'upd_time' => time(),
        	'techn_is_repair'=>1
        ];
        //更新订单状态
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($order_upd_data))
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '订单更新失败']);
			exit();
		}
		//添加状态日志
		$status_array = OrderService::$status_array;
		$order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $order_upd_data['status'],
			'msg' => '退款['.$status_array[$order_info['status']]['name'].'-'.$status_array[$order_upd_data['status']]['name'].']',
			'identity_type' => 'user',
			'identity_id' => $order_info['user_id'],
			'add_time' => time(),
			'reason'=>empty($params['reason'])?'':$params['reason']
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '订单历史状态添加失败']);
			exit();
		}

		//技师未出发结算状态关闭
		$balance_data = [
			'status' => 2,
			'upd_time' => time()
		];
		if(!Db::name('balance')->where(['order_id' => $order_info['id'], 'status' => 0])->update($balance_data))
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '结算记录更新失败']);
			exit();
		}

		//提交事务
		Db::commit();

		//发送模板消息
		//查询技师信息
		$techn_info = Db::name('techn')->where(['id' => $order_info['techn_id']])->find();
		if(!empty($techn_info))
		{

			//给用户推送模板消息
			//查询用户的openid
			$user_openid = Db::name('user_weixin')->where(['user_id' => $order_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
			if(!empty($user_openid))
			{
				$tem_msg = [];
				$tem_msg['touser'] = $user_openid;
				$tem_msg['template_id'] = 'zZ7W-JsnM7OwbWnnuPxodYSCpBrGLOY1X0hKDwFHpT4';
				$tem_msg['url'] = 'https://h5.hexukeji.com/h5/pages/order/orderdetail?order_id='.$order_info['id'];
				$tem_msg['data'] = [
					'first' => [
		                'value' => '退款通知',
		                'color' => '#173177'
		            ],
		            'keyword1' => [
		                'value' => $order_info['order_no'],
		                'color' => '#173177'
		            ],
		            'keyword2' => [
		                'value' => $techn_info['nickname'],
		                'color' => '#173177'
		            ],
		            'keyword3' => [
		                'value' => '技师暂无接单',
		                'color' => '#173177'
		            ],
		            'keyword4' => [
		                'value' => $order_info['total_price'].'元',
		                'color' => '#173177'
		            ],
		            'remark' => [
		                'value' => '退款'.$refund_log_data['refund_price'].'元，感谢您的使用！',
		                'color' => '#173177'
		            ]
				];
				UserWeixinService::send_wx_web_tem_msg($tem_msg);
			}


		}


	
	
	}
	
	
	
}